//
//  SetTableViewController.swift
//  ZNZXSuperMarket
//
//  Created by 四川中农 on 2018/7/31.
//  Copyright © 2018年 四川中农. All rights reserved.
//

import UIKit

class SetTableViewController: BaseTableViewController {

    @IBOutlet weak var cacheLabel: UILabel!
    @IBOutlet weak var versionLabel: UILabel!
    
    var flag = 0 // 0 清除缓存 1 退出登录
    lazy var alertView : AlertContentView = {
        let view = AlertContentView.init(frame: CGRect.init(x: 0, y: 0, width: UIScreen.ScreenWidth, height: UIScreen.ScreenHeight))
        view.backClosure = { [weak self] in
            if self?.flag == 0 {
                PKhud.showProgress(title: "清理中~")
                self?.clearCache()
                Utils.DispatchAfter(after: 2, handler: {
                    PKhud.showText(text: "清理完成~")
                    self?.cacheLabel.text = ""
                })
            }else{
                PKhud.show()
                Utils.DispatchAfter(after: 1, handler: {
                    PKhud.hiden()
                    PKhud.showText(text: "你已退出登录~")
                    Utils.removeAllUserInfo()
                    (UIApplication.shared.delegate as! AppDelegate).addClildCtrl()
//                    NotificationCenter.default.post(name: NSNotification.Name(rawValue: "logined"), object: nil)
//                    self?.tableView.tableFooterView = nil
//                    self?.tabBarController?.selectedIndex = 0
//                    self?.backBarButtonMethon()
                })
            }
        }
        UIApplication.shared.keyWindow?.addSubview(view)
        return view
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Uncomment the following line to preserve selection between presentations
        // self.clearsSelectionOnViewWillAppear = false

        // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
        // self.navigationItem.rightBarButtonItem = self.editButtonItem
        self.title = "系统设置"
        self.calculateCache()
        self.versionLabel.text = "当前版本(V" + (Bundle.main.infoDictionary!["CFBundleShortVersionString"] as! String) + ")"
    }
    
    func calculateCache(){
        DispatchQueue.global(qos: .default).async {
            let cacheSize = String(format: "%.2f",self.fileSizeOfCache())
            DispatchQueue.main.async {
                if cacheSize != "0.00" {
                    self.cacheLabel.text = cacheSize + "M"
                }else{
                    self.cacheLabel.text = ""
                }
            }
        }
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.setNavigationBarHidden(false, animated: true)
    }
    
    // MARK:退出登录
    @IBAction func signOutMethod(_ sender: UIButton) {
        self.flag = 1
        self.alertView.show(withTitle: "确定要退出登录吗？")
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    // MARK: - Table view data source
    override func numberOfSections(in tableView: UITableView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return 1
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return 3
    }

    
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        switch indexPath.row {
        case 0:
            guard Utils.isLogined() else {
                PKhud.showText(text: "请先登录~")
                Utils.goLoginCtrol(ctrl: self, isHidenBottomBar: false)
                return
            }
            let ctrl = Utils.instantiateInitialViewControllerWith(storyBoardName: "Main", identitier: "ChangePassWordTableViewController") as! ChangePassWordTableViewController
            self.navigationController?.pushViewController(ctrl, animated: true)
        case 1:
            self.flag = 0
            self.alertView.show(withTitle: "确定要清除缓存吗？")
        default:
            break
        }
    }
    
    func fileSizeOfCache()-> Double {
        
        // 取出cache文件夹目录 缓存文件都在这个目录下
        
        let cachePath = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.cachesDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).first
        
        //缓存目录路径
        
        // 取出文件夹下所有文件数组
        
        let fileArr = FileManager.default.subpaths(atPath: cachePath!)
        
        //快速枚举出所有文件名 计算文件大小
        
        var size:Double = 0
        
        for file in fileArr! {
            
            // 把文件名拼接到路径中
            
            let path = (cachePath! as NSString).appending("/\(file)")
            
            // 取出文件属性
            
            let floder = try! FileManager.default.attributesOfItem(atPath: path)
            
            // 用元组取出文件大小属性
            
            for (abc, bcd) in floder {
                
                // 累加文件大小
                
                if abc == FileAttributeKey.size {
                    
                    size += bcd as! Double
                }
                
            }
            
        }
        
        let mm = size / 1024 / 1024
        
        return mm
        
    }
    
    func clearCache() {
        
        // 取出cache文件夹目录 缓存文件都在这个目录下
        
        let cachePath = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.cachesDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).first
        
        // 取出文件夹下所有文件数组
        
        let fileArr = FileManager.default.subpaths(atPath: cachePath!)
        
        // 遍历删除
        
        for file in fileArr! {
            
            let path = (cachePath! as NSString).appending("/\(file)")
            
            if FileManager.default.fileExists(atPath: path) {
                do {
                    try FileManager.default.removeItem(atPath: path)
                } catch {
                }
                
            }
            
        }
        
    }

}
